<template>
    <div>

        <!-- 查询条件表单 -->
        <div class="query-form">
            <a-form ref="formRef" :model="queryForm" label-align="left" auto-label-width>
                <a-row justify="start" :gutter="16">
                    <a-col :span="6">
                        <a-form-item field="username" :label="$t('user.columns.username')">
                            <a-input v-model="queryForm.username"
                                :placeholder="$t('common.inputPlaceholder') + $t('user.columns.username')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item field="nickName" :label="$t('user.columns.nickName')">
                            <a-input v-model="queryForm.nickname"
                                :placeholder="$t('common.inputPlaceholder') + $t('user.columns.nickName')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item field="realName" :label="$t('user.columns.realName')">
                            <a-input v-model="queryForm.realname"
                                :placeholder="$t('common.inputPlaceholder') + $t('user.columns.realName')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="6">
                        <a-form-item field="type" :label="$t('role.columns.type')">
                            <a-select v-model="queryForm.type" allow-clear :options="adminTypeOption"
                                :placeholder="$t('common.selectPlaceholder') + $t('role.columns.type')" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
            <div>
                <!-- 查询按钮 -->
                <a-button-group>
                    <a-button type="primary" @click="search">{{ t('common.search') }}</a-button>
                    <a-button @click="clear">{{ t('common.clear') }}</a-button>
                </a-button-group>
            </div>
        </div>

        <!-- 数据表格 -->
        <a-table ref="tableRef" :columns="columns" :data="tableData" :pagination="false" stripe table-layout-fixed
            row-key="id" @select="onSelect" :selected-keys="selectedKeys" :row-selection="rowSelection">
            <template #type="{ record }">
                <a-tag bordered color="blue" v-if="record.type === 1">超级管理员</a-tag>
                <a-tag bordered color="blue" v-else>普通管理员</a-tag>
            </template>
            <template #optional="{ record }">
                <a-button type="text" size="small" @click="openEditModal(record)" :title="$t('common.edit')">
                    <icon-edit />
                </a-button>
                <a-popconfirm :content="$t('common.deleteTip')" @ok="remove(record)" v-if="record.code !== 'admin'">
                    <a-button type="text" status="danger">{{ t('common.remove') }}</a-button>
                </a-popconfirm>
            </template>
            <template #footer>
                <div class="table-footer">
                    <a-button-group>
                        <a-button type="primary" @click="openEditModal()">
                            <template #icon>
                                <icon-plus />
                            </template>
                            {{ t('common.add') }}</a-button>
                        <!-- <a-button @click="clear">
                            <template #icon>
                                <icon-upload />
                            </template>
                            {{ t('common.importFile') }}</a-button>
                        <a-button @click="clear">
                            <template #icon>
                                <icon-download />
                            </template>
                            {{ t('common.exportFile') }}</a-button> -->

                        <a-popconfirm :content="$t('common.deleteTip')" @ok="remove">
                            <a-button status="danger" :disabled="selectedKeys.length === 0">
                                <template #icon>
                                    <icon-delete />
                                </template>
                                {{ t('common.batchDelete') }}</a-button>
                        </a-popconfirm>

                    </a-button-group>

                    <a-pagination v-bind="queryForm.page" show-total @change="changePage" show-page-size
                        :page-size-options="pageSizeOptions" />
                </div>
            </template>
        </a-table>

        <!-- 新增/编辑弹窗 -->
        <a-modal v-model:visible="modalVisiable" :on-before-ok="handleOk" @cancel="closeEditModal"
            @close="closeEditModal">
            <template #title>
                {{ dataFormTitle }}
            </template>
            <div class="role-form">
                <a-card :style="{ width: '360px' }" title="权限树">
                    <a-tree ref="treeRef" v-model:checked-keys="checkedKeys" :checkable="true" check-strictly
                        v-model:expanded-keys="expandedKeys" :data="treeData" :field-names="fieldNames">
                        <template #icon="{ node }">
                            <!-- 0 目录 1 菜单 2 按钮-->
                            <icon-folder v-if="node.type === 0" />
                            <icon-drive-file v-if="node.type === 1" />
                        </template>
                    </a-tree>
                </a-card>
                <a-form :model="dataForm" ref="dataFormRef" :rules="dataFormRules">
                    <a-form-item field="name" :label="$t('role.columns.name')">
                        <a-input v-model="dataForm.name"
                            :placeholder="$t('common.inputPlaceholder') + $t('role.columns.name')" />
                    </a-form-item>
                    <a-form-item field="code" :label="$t('role.columns.code')">
                        <a-input v-model="dataForm.code"
                            :placeholder="$t('common.inputPlaceholder') + $t('role.columns.code')" />
                    </a-form-item>
                    <a-form-item field="type" :label="$t('role.columns.type')">
                        <a-select v-model="dataForm.type" allow-clear :options="adminTypeOption"
                            :placeholder="$t('common.selectPlaceholder') + $t('role.columns.type')" />
                    </a-form-item>
                    <a-form-item field="descn" :label="$t('role.columns.descn')">
                        <a-input v-model="dataForm.descn"
                            :placeholder="$t('common.inputPlaceholder') + $t('role.columns.descn')" />
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>


    </div>
</template>
<script setup>
import { pageSizeOptions } from '@/config/constants';
import { tree } from '@/api/menu.js'
import { table, show, del, save } from '@/api/role.js'
import { options } from '@/api/dict';
import { onMounted, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Message } from '@arco-design/web-vue'
import { roleOption } from '@/api/role';
const { t } = useI18n()

// 表格字段
const columns = [{
    title: t('role.columns.code'),
    dataIndex: 'code',
}, {
    title: t('role.columns.name'),
    dataIndex: 'name',
},
{
    title: t('role.columns.type'),
    slotName: 'type',
},
{
    title: t('role.columns.descn'),
    dataIndex: 'descn',
}, {
    title: t('common.optional'),
    fixed: 'right',
    slotName: 'optional',
    width: 180
}];
// 表格多选
const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    checkStrictly: true
});
const selectedKeys = ref([])
const expandedKeys = ref([])
const onSelect = (rowKeys) => {
    selectedKeys.value = rowKeys
}
// 表格数据
const tableData = ref()
const tableRef = ref()

// 查询表单
const formRef = ref()
// 查询表单条件
const queryForm = reactive({
    code: '',
    name: '',
    type: null,
    page: {
        total: 0,
        pageNo: 1,
        pageSize: 10,
        showTotal: true
    }
})
// 查询表格数据
const search = () => {
    let searchParams = []
    if (queryForm.code) {
        searchParams.push(
            {
                "column": "code",
                "operator": "LIKE",
                "value": queryForm.code,
            }
        )
    }
    if (queryForm.name) {
        searchParams.push(
            {
                "column": "name",
                "operator": "LIKE",
                "value": queryForm.name,
            }
        )
    }
    if (queryForm.type) {
        searchParams.push(
            {
                "column": "type",
                "operator": "EQ",
                "value": queryForm.type,
            }
        )
    }
    let params = {
        "searchParams": searchParams
    }
    table(params).then(res => {
        if (res.code === 200) {
            tableData.value = res.data.records
            queryForm.page.current = res.data.current
            queryForm.page.pageSize = res.data.size
            queryForm.page.total = res.data.total
        } else {
            Message.error(res.message)
        }
    })
}
// 清空查询条件
const clear = () => {
    formRef.value.resetFields()
}

// 加载字典信息
const adminTypeOption = ref([])
const loadDict = (dictType, targetOptions) => {
    options({ dictType: dictType }).then(res => {
        if (res.code === 200) {
            targetOptions.value = res.data
        }
    })
}
// 新增/编辑弹窗
let dataForm = ref({})
const dataFormRef = ref()
const dataFormTitle = ref('')
const modalVisiable = ref(false)
const dataFormRules = {
    name: [
        {
            required: true,
            message: t('common.inputPlaceholder') + t('role.columns.name'),
        },
    ],
    code: [
        {
            required: true,
            message: t('common.inputPlaceholder') + t('role.columns.code'),
        }
    ],
    type: [
        {
            required: true,
            message: t('common.inputPlaceholder') + t('role.columns.type'),
        }
    ],

}

const loading = ref(false)
const roleOptions = ref([])
// 远程搜索角色
const handleSearch = (value) => {
    loading.value = true
    roleOption({ name: value }).then(res => {
        loading.value = false
        if (res.code === 200) {
            roleOptions.value = res.data
        } else {
            Message.error(res.message)
        }
    })

}

// 打开新增/编辑弹窗
const openEditModal = (item) => {
    handleSearch()
    loadTree()
    if (item) {
        show({ id: item.id }).then(res => {
            if (res.code === 200) {
                res.data.type = res.data.type.toString()
                checkedKeys.value = res.data.permissionIds
                dataForm.value = res.data
                modalVisiable.value = true
            } else {
                Message.error(res.message)
            }
        })
        dataFormTitle.value = t('common.edit')
    } else {
        dataFormTitle.value = t('common.add')
        modalVisiable.value = true
    }

}

const handleOk = async () => {
    return await new Promise((resolve) => {
        dataFormRef.value.validate((values) => {
            if (!values) {
                // 验证通过
                dataForm.value.permissionIds = checkedKeys.value
                save(dataForm.value).then(res => {
                    if (res.code === 200) {
                        Message.success(t('common.operateSuccess'))
                        modalVisiable.value = false
                        search()
                        resolve(true)
                    } else {
                        Message.error(res.message)
                        resolve(false)
                    }
                })
            } else {
                resolve(false)
            }
        })
    })
}
// 关闭新增/编辑弹窗
const closeEditModal = () => {
    dataFormRef.value.resetFields()
    checkedKeys.value = []
    dataForm.value = {}
    modalVisiable.value = false
}

const remove = (item) => {
    let deleteIds = []
    if (item) {
        // 单个删除
        deleteIds.push(item.id)
    } else {
        deleteIds = [...selectedKeys.value]
    }
    if (deleteIds.length === 0) {
        Message.warning(t('common.chooseDeleteItem'))
        return
    }
    del({ ids: deleteIds }).then(res => {
        if (res.code === 200) {
            Message.success(t('common.operateSuccess'))
            search()
        } else {
            Message.error(res.message)
        }
    })
}

// 树形菜单
const treeData = ref([])
const treeRef = ref()
const checkedKeys = ref([])
const fieldNames = reactive({
    title: 'name',
    children: 'children',
    icon: () => { }
})
const loadTree = () => {
    tree().then(res => {
        if (res.code === 200) {
            treeData.value = res.data
            expandedKeys.value = expandAll(treeData.value)
        } else {
            Message.error(res.message)
        }
    })
}

const expandAll = (menus) => {
    let expandedKeys = []
    menus.forEach(element => {
        expandedKeys.push(element.key)
        if (element.children && element.children.length > 0) {
            expandedKeys = expandedKeys.concat(expandAll(element.children))
        }
    });
    return expandedKeys
}

onMounted(() => {
    loadDict('admin_type', adminTypeOption)
    search()
})

const changePage = (current) => {
    queryForm.page.current = current
    search()
}
</script>
<style lang="less" scoped>
.arco-tree {
    max-height: calc(100vh - 240px);
    overflow-y: auto;
}

.role-form {
    display: flex;
    flex-direction: row;

}
</style>